﻿using IM.Easy.Core.Audit;
using IM.Easy.Entity.System;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IM.Easy.Entity.Authorization
{
    /// <summary>
    /// 刷新令牌实体类
    /// 用于存储和管理刷新令牌，支持JWT认证的令牌刷新机制
    /// </summary>
    [SugarTable("RefreshToken", TableDescription = "刷新令牌表")]
    public class RefreshToken : AuditSnowflakeEntity
    {
        /// <summary>
        /// 刷新token
        /// </summary>
        [SugarColumn(ColumnName = "Token", ColumnDescription = "刷新token")]
        public string Token { get; set; }

        /// <summary>
        /// 关联的用户ID
        /// 外键，指向Users表的主键
        /// </summary>
        [SugarColumn(ColumnName = "UserId", ColumnDescription = "关联用户ID")]
        public long UserId { get; set; }

        /// <summary>
        /// 令牌过期时间
        /// 表示此令牌的有效期截止时间
        /// </summary>
        [SugarColumn(ColumnName = "Expires", ColumnDescription = "令牌过期时间")]
        public DateTime Expires { get; set; }

        /// <summary>
        /// 令牌撤销时间
        /// 如果令牌被撤销，则记录撤销时间
        /// </summary>
        [SugarColumn(ColumnName = "Revoked", ColumnDescription = "令牌撤销时间")]
        public DateTime? Revoked { get; set; }

        /// <summary>
        /// 替换此令牌的新令牌
        /// 当使用刷新令牌获取新的访问令牌时，会生成新的刷新令牌替换旧令牌
        /// </summary>
        [SugarColumn(ColumnName = "ReplacedByToken", ColumnDescription = "替换此令牌的新令牌", Length = 88)]
        public string? ReplacedByToken { get; set; }

        /// <summary>
        /// 令牌描述或用途说明
        /// 可选的描述字段，用于说明令牌的用途或来源
        /// </summary>
        [SugarColumn(ColumnName = "Description", ColumnDescription = "令牌描述", Length = 255)]
        public string? Description { get; set; }

        /// <summary>
        /// 令牌是否已被撤销
        /// 计算属性，检查Revoked字段是否有值
        /// </summary>
        [SugarColumn(IsIgnore = true)]
        public bool IsRevoked => Revoked != null;

        /// <summary>
        /// 令牌是否已过期
        /// 计算属性，检查当前时间是否超过Expires时间
        /// </summary>
        [SugarColumn(IsIgnore = true)]
        public bool IsExpired => DateTime.Now >= Expires;

        /// <summary>
        /// 令牌是否仍处于活动状态
        /// 计算属性，检查令牌既未被撤销也未过期
        /// </summary>
        [SugarColumn(IsIgnore = true)]
        public bool IsActive => !IsRevoked && !IsExpired;

        /// <summary>
        /// 导航属性 - 关联的用户
        /// 使用SQLSugar的导航属性特性，便于联表查询
        /// </summary>
        [Navigate(NavigateType.OneToOne, nameof(UserId))]
        public SysUser? User { get; set; }
    }
}
